var http = require('http')
var url = require('url')
//var axios = require('axios');
var querystring = require('querystring')

let hostflow = 'http://localhost:8016';
let headers = {
	'Content-Type': 'application/json',
	'HuaYan-Auth-Key': 'FC56C94C57E0AE2C39242466FBAFAAB5480552FC1259852E8230825240843BB1B43A3CDDFBFB9990EAF70746D250F8CDEF45F9A049C66722C5A0A88EA99C67FED85B0AE9EA989A50E84F874008628AB4C936795AE2E2DCDD'
}

function formatResData(data, headers) {
	let type = headers['content-type'];
	if (!type || type && type.indexOf('application/json') !== -1) {
		if (typeof data === 'string') {
			try {
				data = JSON.parse(data)
			} catch (e) {}
		}
	}
	return data;
}

function getdata(url, headers = {}) {
	return new Promise((resolve, reject) => {
		const options = {
			headers: headers
		}
		const req = http.get(url, options, res => {
			let had = false;
			res.setEncoding('utf-8');
			res.on('data', (chunk) => {
				had = true;
				res.data = formatResData(chunk, res.headers);
				resolve(res)
			});
			res.on('end', () => {
				if (had) return;

				resolve(res)
			})
		});
		req.on('error', e => {
			reject(e);
		})
	})
}

function postdata(url, data, headers = {}) {

	return new Promise((resolve, reject) => {
		const options = {
			method: 'POST',
			headers: headers
		}
		const req = http.request(url, options, res => {
			let had = false;
			res.setEncoding('utf8');
			res.on('data', (chunk) => {
				had = true;
				console.log('Response: ' + chunk);
				res.data = formatResData(chunk, res.headers);
				resolve(res);

			});
			res.on('end', () => {
				if (had) return;
				resolve(res)
			})
			res.on('error', e => {
				reject(e);
			})
		});
		req.on('error', e => {
			reject(e)
		});
		data && req.write(data);
		req.end();
	})




}

var server = http.createServer(function(req, res) {
	// 设置cors跨域
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
	res.setHeader('Content-Type', 'application/json')
	res.setHeader('X-Authorization', '1234567890')
	res.setHeader('Authorization', '1234567890')
     res.setHeader('Set-Cookie','SameSite=None')

	switch (req.method) {
		// 设置了cors跨域
		// post请求时，浏览器会先发一次options请求，如果请求通过，则继续发送正式的post请求
		case 'OPTIONS':
			res.statusCode = 200
			res.end()
			break

		case 'GET':
			console.log(req.url);
			var params = url.parse(req.url, true);
			
			if (params.pathname == '/api/backurl') {
				var data = JSON.stringify(items)
				res.write(data)
				res.end()
			} else {
				res.write('服务正常启动')
				res.end()
			}

			break

		case 'POST':
			if (req.url == '/api/backurl') {
				let postParams = ''
				req.on('data', (params) => {
					postParams += params
				})
				req.on('end', () => {
					const paramsObj = querystring.parse(postParams)
					console.log(paramsObj)
				})
				let data = JSON.stringify( {
					"Id": Math.round(Math.random() * 100),
					"Status": "success",
					"Message": "成功"
				})
				res.write(data)
				res.end()
			}  else {
				res.write('post 请求成功')
				let postParams = ''
				req.on('data', (params) => {
					postParams += params
				})
				req.on('end', () => {
					const paramsObj = querystring.parse(postParams)
					console.log(paramsObj)
				})
				let data = JSON.stringify(items)
				res.write(data)
				res.end()
			}
			break
	}
})
server.listen(8080, (err) => {
	if (!err) {
		console.log('http server is start... http://127.0.0.1:8080')
	}
})
